package com.resou.reader.discovery.bookdetail;

import android.util.Log;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.BookListBean;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.StoreService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.DataSupport;
import com.resou.reader.data.bookshelf.BookshelfService;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.UserUtil;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;

public class BookListPresenter extends ResouBasePresenter<IBookListContract.IBookListView> implements IBookListContract.IBookListPresenter {
    private static final String TAG = "BookListPresenter";
    StoreService storeService;

    public BookListPresenter(IBookListContract.IBookListView view) {
        super(view);
        storeService = ApiImp.getInstance().getService(StoreService.class);
    }

    /**
     * 获取书单详情接口
     *
     * @param bookListId 书单id
     * @param page
     */
    @Override
    public void quearBookListDetail(String bookListId, int page) {
        mView.showProgress();
        storeService.quearBookDetail(UserUtil.getToken(), bookListId, page, pageSize).subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers()).subscribe(new Observer<Result<BookListBean>>() {
            @Override
            public void onSubscribe(Disposable d) {
                addCompositeDisposable(d);
            }

            @Override
            public void onNext(Result<BookListBean> listResult) {
                BookListBean.ListBookBean listBookBean = listResult.getData().getListBook();
                totalNum = listBookBean.getTotalPage() * pageSize;
                localNum = (page + 1) * pageSize;
                if (localNum < totalNum) {
                    mView.getSmartRefreshLayout().finishLoadMore();
                    mView.showDetail(listResult.getData());
                } else {
                    if (totalNum == 0) {
                        mView.showEmpty();
                    }
                    mView.getSmartRefreshLayout().finishLoadMoreWithNoMoreData();
                    mView.showDetail(listResult.getData());
                }
            }

            @Override
            public void onError(Throwable e) {
                mView.showEmpty();
                mView.showError(e);
            }

            @Override
            public void onComplete() {
                mView.showContent();
            }
        });
    }

    /**
     * 用户收藏接口调用
     *
     * @param bookListId 书单id
     */
    @Override
    public void collectionBookList(String bookListId) {
        storeService.collectionBook(UserUtil.getToken(), bookListId).subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers()).subscribe(new Observer<Result>() {
            @Override
            public void onSubscribe(Disposable d) {
                addCompositeDisposable(d);
            }

            @Override
            public void onNext(Result result) {
                if (result.getCode() == 0) {
                    mView.collectionSuccess();
                } else {
                    mView.showInfo("收藏失败");
                }
            }

            @Override
            public void onError(Throwable e) {
                mView.showInfo(e.getMessage());
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 取消收藏接口调用
     *
     * @param bookListId 书单id
     */
    @Override
    public void cancellCollection(String bookListId) {
        storeService.deteleCollction(UserUtil.getToken(), bookListId).subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers()).subscribe(new Observer<Result>() {
            @Override
            public void onSubscribe(Disposable d) {
                addCompositeDisposable(d);
            }

            @Override
            public void onNext(Result result) {
                if (result.getCode() == 0) {
                    mView.cancellCollection();
                } else {
                    mView.showInfo("取消收藏失败");
                }
            }

            @Override
            public void onError(Throwable e) {
                mView.showInfo(e.getMessage());
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 点赞接口调用
     *
     * @param bookId
     */
    @Override
    public void bookLike(String bookId) {
        storeService.bookLike(UserUtil.getToken(), bookId)
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result result) {
                        if (result.getCode() == 0) {
                            mView.showPraiseSuccess();
                        } else {
                            mView.showInfo("点赞失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showInfo(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 取消点赞
     *
     * @param bookId
     */
    @Override
    public void cancellBookLike(String bookId) {
        storeService.cancellLike(UserUtil.getToken(), bookId)
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result result) {
                        if (result.getCode() == 0) {
                            mView.showCancellPraise();
                        } else {
                            mView.showInfo("点赞失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showInfo(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    @Override
    public void addBookList_noLogin(BookListBean.ListBookBean.BooksBean book) {
        DataSupport.getInstance().saveCollection(book, "未读", "", 0, 0, 0);
        mView.joinBookList();
    }

    @Override
    public synchronized void requestlocalSysRemoteBookList(List<BookListBean.ListBookBean.BooksBean> booksBeans) {
        Observable.create((ObservableOnSubscribe<List<BookListBean.ListBookBean.BooksBean>>) emitter -> {
            List<BookCollection> list = LitePalHelper.loadShelfBooks();
            for (int i = 0, length = list.size(); i < length; i++) {
                Log.i(TAG, "LitePalHelper:list " + list.get(i).getBookId());
                for (int i1 = 0, length2 = booksBeans.size(); i1 < length2; i1++) {
                    Log.i(TAG, "remote:booksBeans " + booksBeans.get(i1).getNovelId());
                    if (list.get(i).getBookId().equals(booksBeans.get(i1).getNovelId())) {
                        booksBeans.get(i1).setJoin(1);
                        Log.i(TAG, "requestlocalSysRemoteBookList: " + booksBeans.get(i1).getNovelName());
                    }
                }
            }
            emitter.onNext(booksBeans);
        })
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<List<BookListBean.ListBookBean.BooksBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(List<BookListBean.ListBookBean.BooksBean> booksBeans) {
                        mView.showlocalAndRemoteData(booksBeans);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 添加到书单接口调用
     *
     * @param bookId
     */
    @Override
    public void addBookListLogined(String bookId) {
        BookshelfService bookshelfService = ApiImp.getInstance().getService(BookshelfService.class);
        bookshelfService.uploadBooks(UserInstance.getToken(), bookId + "_1", "app")
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new DisposableObserver<Result>() {

                    @Override
                    public void onNext(Result result) {
                        if (result.getCode() == 0) {
                            mView.joinBookList();
                        } else {
                            mView.showInfo("加入失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showInfo(e.getMessage() + "");
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


}
